package main

import (
	"encoding/json"
	"log"
	"net/http"
)

// 定义用户数据结构
type User struct {
	ID   int    `json:"id"`
	Name string `json:"name"`
}

// 内存存储（实际项目中建议使用数据库）
var users = []User{
	{ID: 1, Name: "Alice"},
	{ID: 2, Name: "Bob"},
}

func main() {
	// 注册路由和处理函数
	http.HandleFunc("/", homeHandler)
	http.HandleFunc("/users", usersHandler)

	// 启动服务器
	log.Println("Server starting on :8080")
	if err := http.ListenAndServe(":8080", nil); err != nil {
		log.Fatal("Server failed to start: ", err)
	}
}

// 根路由处理
func homeHandler(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusOK)
	w.Write([]byte("Welcome to Simple API Server"))
}

// /users 路由处理
func usersHandler(w http.ResponseWriter, r *http.Request) {
	w.Header().Set("Content-Type", "application/json")

	switch r.Method {
	case http.MethodGet:
		// 获取用户列表
		json.NewEncoder(w).Encode(users)

	case http.MethodPost:
		// 创建新用户
		var newUser User
		if err := json.NewDecoder(r.Body).Decode(&newUser); err != nil {
			http.Error(w, err.Error(), http.StatusBadRequest)
			return
		}

		users = append(users, newUser)
		w.WriteHeader(http.StatusCreated)
		json.NewEncoder(w).Encode(newUser)

	default:
		http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
	}
}
